package com.cskaoyan.gateway.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.Utils.MallUtil;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.OrderService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.*;
import com.mall.user.IAddressService;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/shopping")
public class OrderController {
    // 引用远程服务，dubbo不检查服务是否注册、超时连接3s后失败
    @Reference(check = false, timeout = 3000)
    OrderService orderService;

    @Reference(timeout = 3000,check = false)
    private OrderCoreService orderCoreService;

    @Reference(timeout = 3000,check = false)
    private OrderQueryService orderQueryService;

    @Reference(timeout = 3000,check = false)
    private IAddressService iAddressService;
    @Autowired
    MallUtil mallUtil;

    //根据id查询一条订单详情
    @GetMapping("order/{id}")
    public ResponseData queryOrderDetail(@PathVariable("id") String orderId) {
        //要模仿原代码书写风格
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();//已经写好的请求对象
        orderDetailRequest.setOrderId(orderId);
        OrderDetailByIdResponse orderDetailResponse = orderService.getOrderDetailById(orderDetailRequest);
        if (orderDetailResponse.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            //返回的响应对象状态码是success
            ResponseData responseData = new ResponseUtil<>().setData(orderDetailResponse.getOrderDetailById());
            return responseData;
        }
        //返回的响应对象状态码是fail，发送错误原因给前端
        return new ResponseUtil<>().setErrorMsg(orderDetailResponse.getMsg());
    }

    //根据id取消订单
    @PostMapping("cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {//接收json请求体
        //要模仿原代码书写风格
        CancelOrderResponse cancelOrderResponse = orderService.cancelOrderById(request);
        if (cancelOrderResponse.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            //返回的响应对象状态码是success
            ResponseData responseData = new ResponseUtil<>().setData(cancelOrderResponse);
            return responseData;
        }
        //返回的响应对象状态码是fail，发送错误原因给前端
        return new ResponseUtil<>().setErrorMsg(cancelOrderResponse.getMsg());
    }

    //根据id删除订单
    @DeleteMapping ("order/{id}")
    public ResponseData deleteOrder(@PathVariable("id") String orderId) {
        //要模仿原代码书写风格
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();//已经写好的请求对象
        deleteOrderRequest.setOrderId(orderId);
        DeleteOrderResponse detailResponse = orderService.deleteOrderById(deleteOrderRequest);
        if (detailResponse.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            //返回的响应对象状态码是success
            ResponseData responseData = new ResponseUtil<>().setData(detailResponse);
            return responseData;
        }
        //返回的响应对象状态码是fail，发送错误原因给前端
        return new ResponseUtil<>().setErrorMsg(detailResponse.getMsg());
    }


    /**
     * 创建订单
     * */
    @PostMapping("/order")
    @ApiOperation("创建订单")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest){


        String token = CookieUtil.getCookieValue(servletRequest, "access_token");
        Long userId = iAddressService.getUserIdByToken(token);
//        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
//        JSONObject object = JSON.parseObject(userInfo);
//        Long uid = Long.parseLong(object.get("uid").toString());
        request.setUserId(userId);
        request.setUniqueKey(UUID.randomUUID().toString());
        CreateOrderResponse response = orderCoreService.createOrder(request);
        if(response.getCode().equals(OrderRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(response.getOrderId());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @GetMapping("/order")
    @ApiOperation("获取当前用户的所有订单")
    public ResponseData order(OrderListRequest orderListRequest,HttpServletRequest request){
        Long userIdByRequest = mallUtil.getUserIdByRequest(request);
        orderListRequest.setUserId(userIdByRequest);
        Map<String, Object> result = orderQueryService.queryOrder(orderListRequest);
        return new ResponseUtil<>().setData(result,"success");
    }
}
